package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.config.GatewayAuthConfig;
import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 认证过滤器
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {

    @Autowired
    private GatewayAuthConfig gatewayAuthConfig;

    /**
     * @param exchange 请求和响应对象
     * @param chain    过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 判断请求路径是否需要拦截,不需要直接放行
        String path = request.getURI().getPath();
        List<String> allowUrls = gatewayAuthConfig.getAllowUrls();
        for (String allowUrl : allowUrls) {
            if (path.endsWith(allowUrl)) {
                return chain.filter(exchange);
            }
        }
        //3. 获取请求头的token信息
        String token = request.getHeaders().getFirst("token");
        //4. token不存在 直接终止请求 返回401
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5. 解析token 解析失败 终止请求 返回401
        try {
            //用工具类解析token获取载荷信息
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //验证token是否过期 -1 0 为有效
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result < 1) {
                Integer userId = (Integer) claimsBody.get("id");
        //6. 获取到token中存储的userId 将userId再写到请求头中,转发到其它微服务
             //改变request mutate.build
            ServerHttpRequest newRequest = request.mutate().header("userId", String.valueOf(userId)).build();
            ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
            //放行
            return chain.filter(newExchange);
            }
        } catch (Exception e) {
            log.error("解析token失败==>{}", e.getMessage());
        }

        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

}
